package hxdb

import (
  "database/sql"
  "strings"
)

// Transaction
type Transaction struct {
  tx *sql.Tx
}

func (t *Transaction) Commit() error {
  return t.tx.Commit()
}

func (t *Transaction) Rollback() error {
  return t.tx.Rollback()
}

func (t *Transaction) Exec(sqlstr string, args ...interface{}) (sql.Result, error) {
  rs, err := t.tx.Exec(sqlstr, args...)
  if err != nil {
    return nil, NewDbError(sqlstr, err)
  }
  return rs, nil
}

func (t *Transaction) Query(sqlstr string, args ...interface{}) ([]map[string]interface{}, error) {
  rows, err := t.tx.Query(sqlstr, args...)
  if err == nil {
    defer rows.Close()
    var result []map[string]interface{}
    result, err = rowsMapper(rows)
    if err == nil {
      return result, nil
    }
  } else if err == sql.ErrNoRows {
    return nil, err
  }
  return nil, NewDbError(sqlstr, err)
}

func (t *Transaction) One(sqlstr string, args ...interface{}) (map[string]interface{}, error) {
  // if no limit keyword in sqlstr, add it
  if !strings.Contains(sqlstr, "LIMIT 1") {
    sqlstr = sqlstr + " LIMIT 1"
  }
  // query and return first one
  rs, err := t.Query(sqlstr, args...)
  if err != nil {
    return nil, err
  }
  return rs[0], nil
}
